package com.innovation.chengzhangriji.ui.adapter;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.util.ChZhRJUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.lang.reflect.TypeVariable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class DTHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    protected CuteTextView txtDay, txtDate, txtName, txtAge, txtTime;

    protected RoundedImageView imageHeadView;

    protected View dateLayout, topLineView, datePointView, bottomLayout, imageLikeLayout;

    protected FrameLayout contentView;

    protected LinearLayout commentLayout;

    protected TextView txtLikeLayout;

    private boolean showLike = false, showComment = false;

    private ArrayList<Integer> ids;

    private ImageButton iBtnShowComment;

    public interface OnClickCommentListener {
        void onClickCommentPosition(DTHolder holder, int position);
        void showCommentDialog(DTHolder holder);
    }

    public OnClickCommentListener getOnClickCommentListener() {
        return onClickCommentListener;
    }

    public void setOnClickCommentListener(OnClickCommentListener onClickCommentListener) {
        this.onClickCommentListener = onClickCommentListener;
    }

    private OnClickCommentListener onClickCommentListener;

    public DTHolder(View itemView) {
        super(itemView);
//        itemView.setOnLongClickListener(this);
        setupView(itemView);
    }

    public final int getY() {
        return (int) (getContent().getHeight() + itemView.getPaddingTop() + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, contentView.getContext().getResources().getDisplayMetrics()));
    }

    public final int getContentWidth() {
        RelativeLayout layout = ((RelativeLayout)getContent().getParent());
        DisplayMetrics displayMetrics = layout.getResources().getDisplayMetrics();
        return displayMetrics.widthPixels - (int)ChZhRJUtils.dp2px(80, displayMetrics) - layout.getPaddingLeft() - layout.getPaddingRight();
    }

    // 初始化视图
    private void setupView(View itemView) {
        txtDay = (CuteTextView) itemView.findViewById(R.id.text_day);
        txtDate = (CuteTextView) itemView.findViewById(R.id.text_date);
        txtName = (CuteTextView) itemView.findViewById(R.id.text_name);
        txtAge = (CuteTextView) itemView.findViewById(R.id.text_baby_age);
        txtTime = (CuteTextView) itemView.findViewById(R.id.text_time);
        txtLikeLayout = (TextView) itemView.findViewById(R.id.text_like);
        imageHeadView = (RoundedImageView) itemView.findViewById(R.id.image_head);

        dateLayout = itemView.findViewById(R.id.date_layout);
        topLineView = itemView.findViewById(R.id.top_line);
        contentView = (FrameLayout) itemView.findViewById(R.id.content_holder);
        datePointView = itemView.findViewById(R.id.image_date_point);
        bottomLayout = itemView.findViewById(R.id.layout_bottom);
        imageLikeLayout = itemView.findViewById(R.id.image_like_left);
        commentLayout = (LinearLayout) itemView.findViewById(R.id.layout_comment);

        // 点击显示评论 Dialog
        iBtnShowComment = (ImageButton) itemView.findViewById(R.id.image_show_comment);
        iBtnShowComment.setOnClickListener(this);

        ids = new ArrayList<Integer>();
    }

    /**
     * 设置当前时间节点的值
     * @param milliseconds the milliseconds from 1970-01-01T00:00:00Z
     */
    public void setDate(long milliseconds) {
        Date date = new Date(milliseconds);
        txtDay.setText(String.valueOf(date.getDate()));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM");
        txtDate.setText(dateFormat.format(date));
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        txtTime.setText(timeFormat.format(date));
    }

    /**
     * 设置评论区域是否显示
     * @param visible
     */
    public void setCommentLayoutIsVisible(boolean visible) {
        showComment = visible;
        if(visible) {
            bottomLayout.setVisibility(View.VISIBLE);
        } else {
            bottomLayout.setVisibility(View.GONE);
        }
    }


    /**
     * 设置点赞是否显示
     * @param visible
     */
    public void setLikeIsVisible(boolean visible) {
        showLike = visible;
        if(visible) {
            imageLikeLayout.setVisibility(View.VISIBLE);
            txtLikeLayout.setVisibility(View.VISIBLE);
        } else {
            imageLikeLayout.setVisibility(View.GONE);
            txtLikeLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 设置点赞列表
     * @param likeList
     */
    public void setLikeList(ArrayList<String> likeList) {
        if (likeList == null) {
            return;
        }
        String content = "";
        for (int i = 0; i < likeList.size(); i++) {
            if (i < likeList.size() - 1) {
                content += likeList.get(i) + ",";
            } else {
                content += likeList.get(i);
            }
        }
        txtLikeLayout.setIncludeFontPadding(false);
        txtLikeLayout.setText(content);
    }

    /**
     * 设置评论列表
     * @param commentList
     */
    public void setCommentList(Context context, ArrayList<DTAdapter.CommentModel> commentList) {
        if (commentList == null) {
            return;
        }
        ids.clear();
        commentLayout.removeAllViews();
        boolean multi;
        // [0]起点1
        // [1]长度1
        // [2]起点2
        // [3]长度2
        int[][] color = new int[commentList.size()][4];
        for (int i = 0; i < commentList.size(); i++) {
            String content = "";
            if (!TextUtils.isEmpty(commentList.get(i).getUserName2())) {
                multi = true;
                color[i][0] = 0;
                content += commentList.get(i).getUserName1() + " 回复 " + commentList.get(i).getUserName2() + ": " + commentList.get(i).getContent();
                color[i][1] = (commentList.get(i).getUserName1() == null ? 4 : commentList.get(i).getUserName1().length());
                color[i][2] = color[i][1] + 4;
                color[i][3] = color[i][2] + (commentList.get(i).getUserName2() == null? 4 : commentList.get(i).getUserName2().length()) + 1;
            } else {
                multi = false;
                color[i][0] = 0;
                content += commentList.get(i).getUserName1() + ": " + commentList.get(i).getContent();
                color[i][1] = (commentList.get(i).getUserName1() == null? 4 : commentList.get(i).getUserName1().length()) + 1;
            }

            ForegroundColorSpan colorSpan = new ForegroundColorSpan(0xff7f3fa2);
            SpannableStringBuilder builder = new SpannableStringBuilder(content);
            if (multi) {
                builder.setSpan(colorSpan, color[i][0], color[i][1], Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(0xff7f3fa2);
                builder.setSpan(colorSpan2, color[i][2], color[i][3], Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                builder.setSpan(colorSpan, color[i][0], color[i][1], Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            TextView textView = new TextView(context);
            textView.setId(i);
            textView.setTextSize(12);
            textView.setTextColor(Color.BLACK);
            textView.setText(builder);
            textView.setIncludeFontPadding(false);
            float paddingTop = ChZhRJUtils.dp2px(9, itemView.getResources().getDisplayMetrics());
            float paddingLeft = ChZhRJUtils.dp2px(8, itemView.getResources().getDisplayMetrics());
            if(i == 0) {
                if(showLike) {
//                    textView.setBackgroundColor(Color.BLUE);
                    textView.setPadding((int)paddingLeft, (int)(paddingTop / 3), (int)paddingLeft, (int)(paddingTop / 2));
                } else {
                    textView.setPadding((int)paddingLeft, (int)(paddingTop * 2 / 3), (int)paddingLeft, (int)(paddingTop / 2));
                }
            }
            else if(i == commentList.size() - 1) {
                textView.setPadding((int)paddingLeft, (int)(paddingTop / 2), (int)paddingLeft, (int)(paddingTop * 2 / 3));
            }
            else {
                textView.setPadding((int)paddingLeft, (int)(paddingTop / 2), (int)paddingLeft, (int)(paddingTop / 2));
            }
            textView.setOnClickListener(this);
            commentLayout.addView(textView);
            ids.add(i);
        }
    }


    /**
     * 设置评论是否显示
     * @param visible
     */
    public void setCommentIsVisible(boolean visible) {
        if(visible) {
            commentLayout.setVisibility(View.VISIBLE);
        } else {
            commentLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 设置发表当前日记人的称谓
     * @param name 称谓名称
     */
    public void setUserName(String name) {
        txtName.setText(name);
    }

    /**
     * 设置宝宝的年龄
     * @param age 宝宝的年龄
     */
    public void setAge(String age) {
        txtAge.setText(age);
    }

    /**
     * 设置发表日记人的头像
     * @param url 头像
     */
    public void setImageUserHeadUrl(String url) {
        ImageLoader.getInstance().displayImage(url, imageHeadView, Config.getOptionsHead());
    }

    /**
     * 设置是否显示日期节点
     */
    public void setDateIsVisible(boolean visible) {
        if(visible) {
            dateLayout.setVisibility(View.VISIBLE);
            datePointView.setVisibility(View.VISIBLE);
        } else {
            dateLayout.setVisibility(View.INVISIBLE);
            datePointView.setVisibility(View.GONE);
        }
    }

    /**
     * 设置是否显示节点上标线 (第一条不显示)
     */
    public void setTopLineVisible(boolean visible) {
        if(visible) {
            topLineView.setVisibility(View.VISIBLE);
        } else {
            topLineView.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 获取内容区域
     */
    public FrameLayout getContent() {
        return contentView;
    }

    @Override
    public void onClick(View v) {
        if(onClickCommentListener != null) {
            if(v.getId() == R.id.image_show_comment) {
                // System.out.println("点击了回复按钮");
                onClickCommentListener.showCommentDialog(this);
            } else {
                for (int i : ids) {
                    if (v.getId() == i) {
                        onClickCommentListener.onClickCommentPosition(this, i);
                        return;
                    }
                }
            }
        }

    }
}
